<?php
namespace Secret\Controllers;

use Secret\Common\Utils;
use Silex\Application;
use Silex\ControllerProviderInterface;
use Silex\ControllerCollection;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\Serializer\Normalizer\GetSetMethodNormalizer;
use Symfony\Component\HttpFoundation\Response;

class ModelCSP implements ControllerProviderInterface {

	public function connect(Application $app) {
		$controllers = $app['controllers_factory'];
		$controllers->match('/', array($this,'models'), 'GET')->bind('models');
		$controllers->match('/sort/', array($this,'sort'), 'POST')->bind('sort-models');
		$controllers->match('/detail/{type}/{returnURL}/', array($this,'model'), 'GET')->bind('add-model');
		$controllers->match('/detail/{type}/{returnURL}/{name}/', array($this,'model'), 'GET')->bind('edit-model');
		$controllers->match('/{type}/', array($this,'models'), 'GET')->bind('models-with-type');
		return $controllers;
	}

	public function models(Application $app, $type = 0) {
		$models = $app['em']->createQueryBuilder()
			->from('Secret\Entities\Model', 'entity')
			->select('entity')
			->where('entity.type = :v1')
			->setParameter('v1', $type)
			->orderBy('entity.rank', 'ASC')
			->getQuery()
			->getResult(\Doctrine\ORM\Query::HYDRATE_ARRAY);
		return $app['twig']->render("models.twig", array(
			'models' => $models, 
			'type' => $type,
			'returnURL' => \Secret\Common\Utils::getURL(),
		));
	}

	public function model(Application $app, $type, $returnURL, $name = null) {
		global $CMS_COLUMN_META, $CMS_COLUMN_TYPES, $CMS_COLUMN_TYPES_CUSTOM;
		$contentTable = $app['em']->getClassMetadata('Secret\Entities\Content');
		$content = array();
		$content['type'] = $type;
		$content['returnURL'] = urldecode($returnURL);
		$content['fields'] = $contentTable->getFieldNames();
		$content['meta'] = $CMS_COLUMN_META;
		$content['types'] = $CMS_COLUMN_TYPES;
		sort($content['fields'], SORT_NATURAL);
		sort($content['meta'], SORT_NATURAL);
		ksort($content['types'], SORT_NATURAL);
// 		$content['types'] = array_merge($content['types'], array_keys($CMS_COLUMN_TYPES_CUSTOM));
		
		$name = urldecode($name);
		$result = $app['em']->createQueryBuilder()
			->from('Secret\Entities\Model', 'entity')
			->select('entity')
			->where('entity.name = :v1')
			->setParameter('v1', $name)
			->orderBy('entity.rank', 'ASC')
			->getQuery()
			->getResult(\Doctrine\ORM\Query::HYDRATE_ARRAY);
		$content['model'] = count($result) > 0 ? $result[0] : null;
		$result = $app['em']->createQueryBuilder()
			->from('Secret\Entities\Model', 'entity')
			->select('entity')
			->orderBy('entity.rank', 'DESC')
			->setMaxResults(1)
			->getQuery()
			->getResult(\Doctrine\ORM\Query::HYDRATE_ARRAY);
		$content['rank'] = count($result) > 0 ? $result[0]['rank'] : 0;
		$request = $app['request'];
		if ($request->getMethod() == 'POST') {
			$obj = json_decode($request->request->get('obj'));
			$entity = new \Secret\Entities\Model();
			if ($obj->id) {
				$repo = $app['em']->getRepository('Secret\Entities\Model');
				$entity = $repo->find($obj->id);
			}
			if ($request->get('action') == 'Submit' || $request->get('action') == 'Submit & back') {
				$entity->setName($obj->name);
				$entity->setRank($obj->rank);
				$entity->setDefaultSortBy($obj->defaultSortBy);
				$entity->setIdField($obj->idField);
				$entity->setNumPerPage($obj->numPerPage);
				$entity->setVisible($obj->visible);
				$entity->setResortable($obj->resortable);
				$entity->setColumnsJson($obj->columnsJson);
				$entity->setType($obj->type);
				$entity->setPermission($obj->permission);
				$entity->setOwnList($obj->ownList);
				$entity->setOwnDetail($obj->ownDetail);
				$entity->setTwigList($obj->twigList);
				$entity->setTwigDetail($obj->twigDetail);
				$app['em']->persist($entity);
				$app['em']->flush();
				if ($request->get('action') == 'Submit & back') {
					return $app->redirect($content['returnURL']);
				}
				return $app->redirect('/secret/models/detail/' . $type . '/' . urlencode($returnURL) . '/' . urlencode($entity->getName()) . '/');
			} else {
				if ($request->get('action') == 'Remove') {
					$app['em']->remove($entity);
					$app['em']->flush();
					return $app->redirect($content['returnURL']);
				}
			}
		}
		return $app['twig']->render("model.twig", $content);
	}

	public function sort(Application $app) {
		$request = $app['request'];
		$data = json_decode($request->get('data'));
		$repo = $app['em']->getRepository('Secret\Entities\Model');
		foreach ($data as $idx => $itm) {
			$entity = $repo->find($itm);
			if ($entity) {
				$entity->setRank($idx);
				$app['em']->persist($entity);
			}
		}
		$app['em']->flush();
		return new Response('Success');
	}
}